const dbFn = require("../../database/vod/query")
const dayjs = require('dayjs')
const fs = require("fs")
const path = require("path")

// 讲师条件查询分页
const handlerFindQueryPage = async (req, res) => {
  // 分页/搜索 查询
  const { params } = req
  const { page, pageSize } = params
  // 如果有searchObj 则搜索
  const searchObj = req.body
  const start = (page - 1) * pageSize
  const end = page * pageSize

  let sql = '', resultTotal = []
  if (Object.keys(searchObj).length > 0) {
    sql = `SELECT * FROM teacher WHERE is_deleted=0`
    let rangeSql = ''
    // 提取出搜索的时间字段
    let rangeObj = {}
    if (searchObj['joinDateBegin'] && searchObj['joinDateEnd']) {
      rangeObj['joinDateBegin'] = searchObj['joinDateBegin']
      rangeObj['joinDateEnd'] = searchObj['joinDateEnd']
      // 拼接搜索时间字段
      rangeSql = `${res.getRangeSql(rangeObj, ['join_date','joinDateBegin','joinDateEnd'])}`
    }
    delete searchObj['joinDateBegin']
    delete searchObj['joinDateEnd']
    // 拼接搜索条件
    let searchSql = `${dbFn.getSearchSql(searchObj)}`
    sql += `${searchSql} ${rangeSql}`
    console.log(sql)
  } else {
    sql = `SELECT * FROM teacher where is_deleted=0 LIMIT ${start}, ${end}`
    // 获取讲师总数
    const sqlCount = `SELECT COUNT(*) AS total FROM teacher WHERE is_deleted=0`
    resultTotal = await dbFn.sqlExcute(sqlCount)
  }

  let result = await dbFn.sqlExcute(sql, searchObj)
  res.send({
    status: 1,
    code: 20000,
    data: {
      records: result,
      total: resultTotal[0]?.total ? resultTotal[0].total : result.length,
    },
  })
}

// 添加讲师
const handlerSaveTeacher = async (req, res) => {
  const teacherInfo = req.body
  const sql = `INSERT INTO teacher set ?`
  const result = await dbFn.sqlExcute(sql, teacherInfo)
  res.send({
    status: 1,
    code: 20000,
    data: {
      result,
    },
  })
}

// 讲师头像上传
const handlerUpload = async (req, res) => {
  console.log(req.file)
  const originalname = req.file.originalname

  let oldname = req.file.path //获取path: 'public\\upload\\0f625978d5d1a783b12e149718f8b634',
  //let newname = req.file.path + path.parse(req.file.originalname).ext //.jpg
  let newname = path.join(__dirname, '../../public/upload/avatar/' + originalname)
  fs.renameSync(oldname, newname)//将老的文件名改成新的有后缀的文件 #同步写法

  res.send({
    status: 1,
    code: 20000,
    data: 'http://127.0.0.1:8080/uploads/avatar/' + originalname

  })
}

// 根据id查询讲师
const handlerFindById = async (req, res) => {
  const { id } = req.params
  const sql = `SELECT * FROM teacher WHERE id = ${id} and is_deleted=0`
  const result = await dbFn.sqlExcute(sql)
  res.send({
    status: 1,
    code: 20000,
    data: {
      ...result[0],
    },
  })
}

// 更新讲师
const handlerUpdateTeacher = async (req, res) => {
  const teacherInfo = req.body
  // 转换join_date为时间日期
  teacherInfo.join_date = dayjs(teacherInfo.join_date).format('YYYY-MM-DD')
  // 创建时间
  teacherInfo.create_time = dayjs(teacherInfo.create_time).format('YYYY-MM-DD HH:mm:ss')
  // 更新时间
  teacherInfo.update_time = dayjs(teacherInfo.update_time).format('YYYY-MM-DD HH:mm:ss')
  // 执行更新
  const sql = `UPDATE teacher set ? WHERE id = ${teacherInfo.id}`
  const result = await dbFn.sqlExcute(sql, teacherInfo)
  res.send({
    status: 1,
    code: 20000,
    data: {
      ...result,
    },
  })
}

// 删除讲师
const handlerDeleteTeacher = async (req, res) => {
  const { id } = req.params
  // 软删除
  const sql = `UPDATE teacher set is_deleted = 1 WHERE id = ${id}`
  const result = await dbFn.sqlExcute(sql)
  res.send({
    status: 1,
    code: 20000,
    data: {
      ...result,
    },
  })
}

// 批量删除讲师
const handlerDeleteTeacherBatch = async (req, res) => {
  const idList = req.body
  // 软删除
  const sql = `UPDATE teacher set is_deleted = 1 WHERE id in (${idList})`
  const result = await dbFn.sqlExcute(sql)
  res.send({
    status: 1,
    code: 20000,
    data: {
      ...result,
    },
  })
}

// 查询所有讲师
const handlerFindAll = async (req, res) => {
  const sql = `SELECT * FROM teacher WHERE is_deleted=0`
  const result = await dbFn.sqlExcute(sql)
  res.send({
    status: 1,
    code: 20000,
    data: {
      ...result,
    },
  })
}

module.exports = {
  handlerFindQueryPage,
  handlerSaveTeacher,
  handlerUpload,
  handlerFindById,
  handlerUpdateTeacher,
  handlerDeleteTeacher,
  handlerDeleteTeacherBatch,
  handlerFindAll,
}
